map

A collection in Scala is a data structure which holds a group of objects. Examples of collections include Arrays, Lists, etc. We can apply some transformations to these collections using several methods. One such widely used method offered by Scala is map().

Important points about map() method:

  • map() is a higher order function.
  • Every collection object has the map() method.
  • map() takes some function as a parameter.
  • map() applies the function to every element of the source collection.
  • map() returns a new collection of the same type as the source collection.


// Scala program to
// transform a collection
// using map()

//Creating object
object Demo
{
// square of an integer
def square(a:Int):Int
=
{
a*a
}

// Main method
def main(args:Array[String])
{
// source collection
val collection = List(1, 3, 2, 5, 4, 7, 6)
// transformed collection
val new_collection = collection.map(square)
println(new_collection)
}
}


// Scala program to
// transform a collection
// using map()

//Creating object
object Demo
{
// Main method
def main(args:Array[String])
{
// source collection
val collection = List(1, 3, 2, 5, 4, 7, 6)
// transformed collection
val new_collection = collection.map(x => x * x )
println(new_collection)
}
}














No comments:

Post a Comment